// Import System requirements
import Vue from 'vue'



//vuex store
import store from './store'
//routes
import router from './router'
//
import './http'
//filters
import { notescape,time} from './filters'

import util from './utilHelper'

import AppView from './App.vue'

// Import Install and register helper items
Vue.filter('notescape', notescape);
Vue.filter('time', time);


Vue.prototype['utilHelper'] = util;
// Resource logic
Vue.http.options.root = '';
Vue.http.options.emulateJSON = true;
Vue.http.interceptors.push((request, next) => {
	let _showError=request['showError'];
	next((response) => {
		//只有response.ok会到resolve里面；
		console.log(response);
		if(response.status==401){
			store.commit('UNSET_USER');
			window.localStorage.removeItem('token');
			window.localStorage.removeItem('username');
			delete Vue.http.headers.common['Authorization'];
			router.push({
				path: '/login'
			})
		}
		if(!response.ok||response.data.status=='fail'){
			response.ok=false; //直接进入catch
			console.log('fail');
			let msg=(response.data?response.data.msg:'')||'反正没成功！大概是网络故障';
			switch (_showError){
				case 1:
					//弹出层覆盖整个页面
					util.showError(msg,1);
					break;
				case 2:
					//弹出层弹出错误信息
					util.showError(msg,2);
					break;
				default:
					console.log(msg);
			}
		}else {
			console.log('success');
		}

		return response;
	})
});




// Routing logic

// Some middleware to help us ensure the user is authenticated.
router.beforeEach((to, from, next) =>{
	next();
	if (to.matched.some(record => record.meta.requiresAuth)&&!store.state.user.token) {
		// this route requires auth, check if logged in
		// if not, redirect to login page.
		router.push({
			path: '/login',
			query: { redirect: to.fullPath }
		})
	}
});
//todo 这里有点烂，暂时这么处理吧;
router.afterEach(route => {
	//未关闭错误的情况下跳页
	util.hideError();
})


//localStorage
// window.localStorage.removeItem('token');
// window.localStorage.removeItem('username');
if (window.localStorage.getItem('token')&&window.localStorage.getItem('username')) {
	let token=window.localStorage.getItem('token');
	let username=window.localStorage.getItem('username');
	store.commit('SET_TOKEN',token);
	store.commit('SET_USERNAME',username);
	window.localStorage.setItem('token',token);
	window.localStorage.setItem('username',username);
	Vue.http.headers.common['Authorization'] = token;
}
// Start out app!
// eslint-disable-next-line no-new
new Vue({
	router: router,
	store: store,
	...AppView
}).$mount('#root')

